import ajax from "@/util/request";
import { ElMessageBox } from "element-plus";
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import {setupListReturn} from "../setup";

function setupList(type: string): setupListReturn;

function setupList(type: {
    modelName: string,
    queryURL?: string,
    deleteURL?: string,
    pk?: string,
    defaultFormData?: IStringKey
}): setupListReturn;

/**
 * 返回一个方法，调用后获取列表组件所需要用到的属性和方法
 * @param modelName 模块名
 * @param queryURL 查询地址，默认为/${modelName}/queryList
 * @param deleteURL 删除地址，默认为`/${modelName}/delete`
 * @param pk 删除时要传递的主键，默认为`t_${modelName}_pk`
 * @returns 
 */
function setupList(param: string | {
    modelName: string,
    queryURL?: string,
    deleteURL?: string,
    pk?: string,
    defaultFormData?: IStringKey
}): setupListReturn {

    let modelName: string;
    let deleteURL: string;
    let queryURL: string;
    let pk: string;
    let defaultFormData: IStringKey;
    if (typeof param == 'object') {
        modelName = param.modelName;
        queryURL = param.queryURL ?? `/${modelName}/queryList`;
        deleteURL = param.deleteURL ?? `/${modelName}/delete`;
        pk = param.pk ?? `t_${modelName}_pk`;
        defaultFormData = param.defaultFormData ?? {pageSize:20};
    } else {
        modelName = param;
        queryURL = `/${modelName}/queryList`;
        deleteURL = `/${modelName}/delete`;
        pk = `t_${modelName}_pk`;
        defaultFormData = {pageSize:20};
    }

    const myForm = ref<FormInstance>();

    const showObj = reactive<any>({});

    const rowData = ref<any>({});

    const formData = reactive<any>({...defaultFormData});

    const useObj = reactive<any>({ });

    const tableData = reactive<Array<object>>([]);

    const total = ref<number>(0);

    /**
     * 将当前表单数据提交进行查询
     */
    function handleQuery(currentPage: number) {
        formData.currentPage = currentPage;
        // 需要后台返回总行数
        formData.needCount = true;
        // console.log("查询：",queryURL);
        ajax(queryURL, formData).then(({ data }) => {
            // 查询成功，将结果数据赋值到tableData中
            if (data.code > 0) {
                // console.log("查询结果：",res.data.data);
                tableData.length = 0;
                tableData.push(...data.data);

                total.value = data.total;
            }
        });
    }

    /**
     * 点击重置按钮：
     * 清空表单，完成数据查询
     */
    function handleReset(myForm: FormInstance | undefined) {
        if (myForm) {    
            myForm.resetFields();
        }
        console.log("重置功能！");
        Object.assign(formData,defaultFormData);
        handleQuery(1);
    }

    function handleDelete(row: any) {
        ElMessageBox.confirm("确认删除该选项吗，删除后将不可恢复?", "删除确认", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            //  调用删除接口
            console.log("我要删除数据：", row,"deleteURL = ",deleteURL);
            const deleteData: IStringKey = {};
            deleteData[pk] = row[pk];
            ajax({url:deleteURL,data: deleteData}).then(
                ({ data }) => {
                    if (data.code > 0) {
                        alert({ message: "删除成功", type: "success" });
                        // 删除成功后，重置表单
                        handleReset(myForm.value);
                    }
                }
            );
        });
    }

    /**
     * 显示组件
     * @param obj 要显示的组件对象
     * @param row 
     */
    function handleShow(obj: IStringKey<boolean>, row?:object) {
        for (const key in obj) {
            if (!showObj[key]) {
                showObj[key] = true;
            }
            if (!useObj[key]) {
                useObj[key] = true;
            }
        }
        if (row) {
            rowData.value = { ...row };
        }
    }

    /**
     *
     * @param pageSize 每页行数变化
     */
    function handleSizeChange(pageSize: number) {
        formData.pageSize = pageSize;
        handleQuery(1);
    }

    /**
     * 当前页数变化
     */
    function handleCurrentChange(currentPage: number) {
        handleQuery(currentPage);
    }

    /**
     * 关闭功能
     * @param updated 是否有新数据更新（或更新的数据）
     */
    function handleClose(updated: boolean | any) {
        for (const key in showObj) {
            showObj[key] = false;
        }
        if (updated) {
            handleReset(myForm.value);
        }
    }



    // 返回对象
    return {
        myForm, formData, rowData, tableData, total, showObj, useObj, handleClose,
        handleQuery, handleReset, handleDelete,
        handleShow, handleSizeChange, handleCurrentChange
    }
}

export default setupList;